/***************************************************************************
 *   Copyright (C) 2007 by Jablonkai Tamás                                 *
 *   tamas.jablonkai@gmail.com                                             *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "popupwidget.h"

#include <QtGui>

#include "dictionarymanager.h"


PopupWidget::PopupWidget(QWidget *parent) : QWidget(parent, Qt::Popup)
{
    textBrowser = new QTextBrowser(this);

    closeTimer = new QTimer(this);
    connect(closeTimer, SIGNAL(timeout()), this, SLOT(close()));
    connect(closeTimer, SIGNAL(timeout()), closeTimer, SLOT(stop()));

    hide();
}


PopupWidget::~PopupWidget()
{
}


void PopupWidget::slotScan(bool b)
{
    if (b)
    {
        prevSelection = qApp->clipboard()->text(QClipboard::Selection);
        timerId = startTimer(300);
    }
    else
        killTimer(timerId);
}


void PopupWidget::enterEvent(QEvent*)
{
    closeTimer->stop();
}


void PopupWidget::leaveEvent(QEvent*)
{
    closeTimer->start(200);
}


void PopupWidget::timerEvent(QTimerEvent*)
{
    QString selection = qApp->clipboard()->text(QClipboard::Selection);
    if (prevSelection != selection)
    {
        prevSelection = selection;
        search();
    }
}


void PopupWidget::search()
{
    DictionaryModel *dict = DictionaryManager::instance()->popupDictionary();
    if (!dict)
        return;

    textBrowser->setHtml(dict->popupSearch(prevSelection));
    textBrowser->adjustSize();
    move(cursor().pos() - QPoint(30, 30));
    show();
}
